import React, { useCallback, useEffect, useState } from 'react';

import BuildTitle from '@/components/BuildTitle';

import { IDefined } from './type';

import { Modal, Card, Button, Input } from 'antd';

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';

import _ from 'lodash';

import ScrollBarLayout from '@/components/ScrollBarLayout';

const CardStyle: React.CSSProperties = {
  height: '20rem',
  overflowX: 'auto',
  overflowY: 'hidden',
  padding: 0,
};

function s4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

// 重新记录数组顺序
const reorder = (list: any, startIndex: any, endIndex: any) => {
  const result = Array.from(list);

  const [removed] = result.splice(startIndex, 1);

  result.splice(endIndex, 0, removed);
  return result;
};

export const NodeDefinedModal: React.FC<IDefined> = ({
  title,
  onClose,
  onFormChange,
  defaultValue,
}) => {
  const className = 'class' + parseInt(String(Math.random() * 1000000));
  const modalTitle = (
    <BuildTitle title={title + '设置' ?? '弹窗'} className={className} />
  );

  const [definedList, setDefinedList] = useState<Record<string, any>[]>([]);

  useEffect(() => {
    if (defaultValue) {
      setDefinedList(defaultValue);
    }
  }, [defaultValue]);

  const onDragEnd = (result: any) => {
    if (!result.destination) {
      return;
    }

    const items: any = reorder(
      definedList,
      result.source.index,
      result.destination.index,
    );

    setDefinedList(items);
  };

  const onAppendDrag = useCallback(() => {
    const lastArray = _.cloneDeep(definedList);

    const definedChild = {
      id: s4() + '-' + s4(),
      seq: lastArray.length,
      mark: s4() + '-' + s4(),
      label: '',
    };

    lastArray.push(definedChild);

    setDefinedList(lastArray);
  }, [definedList]);

  const onDragInputChange = useCallback(
    (targetId, value) => {
      let newDefine = definedList?.map((item) => {
        if (item?.id === targetId) {
          return {
            ...item,
            label: value,
          };
        }

        return {
          ...item,
        };
      });

      setDefinedList(newDefine);
    },
    [definedList],
  );

  // // 设置样式
  const getItemStyle = (isDragging: any, draggableStyle: any) => ({
    background: isDragging ? 'rgba(24,144,255,0.1)' : 'none',
    color: isDragging ? '#ffffff' : '#000000',
    border: isDragging ? '1px solid rgba(24,144,255,0.7)' : 'none',
    width: '100%',
    marginBottom: '.75rem',
    padding: '.5rem',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    ...draggableStyle,
  });

  const onOk = () => {
    onFormChange(definedList);
    onClose();
  };

  const onDelete = (index: number) => {
    const newDefine = _.cloneDeep(definedList);

    if (newDefine?.length > 0) {
      newDefine?.splice(index, 1);
    }

    setDefinedList(newDefine);
  };

  return (
    <Modal
      open={true}
      className={className}
      title={modalTitle}
      onCancel={onClose}
      width={'33%'}
      bodyStyle={{ padding: '.75rem' }}
      onOk={onOk}
    >
      <Card
        size="small"
        extra={
          <>
            <Button icon={<PlusOutlined />} size="small" onClick={onAppendDrag}>
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              size="small"
              style={{ marginLeft: '.5rem' }}
              onClick={() => {
                setDefinedList([]);
              }}
            >
              清空
            </Button>
          </>
        }
        bodyStyle={CardStyle}
      >
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="droppable">
            {(provided: any, snapshot: any) => (
              <div
                {...provided.droppableProps}
                ref={provided.innerRef}
                style={{
                  height: '100%',
                  overflow: 'hidden',
                }}
                // className={styles.DragList}
              >
                <ScrollBarLayout style={{ padding: '.5rem' }}>
                  {definedList?.map((item, index) => (
                    <Draggable
                      key={item?.id}
                      draggableId={item?.id}
                      index={index}
                    >
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          style={{
                            ...getItemStyle(
                              snapshot.isDragging,
                              provided.draggableProps.style,
                            ),
                          }}
                        >
                          <Input
                            placeholder={`请输入字段键值（id:${item?.id}）`}
                            onChange={(e) => {
                              let value = e.target.value;
                              onDragInputChange(item?.id, value);
                            }}
                            value={item?.label}
                          />
                          <Button
                            icon={<DeleteOutlined />}
                            danger
                            size="small"
                            type="text"
                            style={{ margin: '0rem .5rem' }}
                            onClick={() => onDelete(index)}
                          ></Button>
                        </div>
                      )}
                    </Draggable>
                  ))}
                </ScrollBarLayout>
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      </Card>
    </Modal>
  );
};
